package com.eesujie.xcs.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eesujie.xcs.entity.po.NoteCommentPO;
import com.eesujie.xcs.entity.vo.NoteCommentVO;
import com.eesujie.xcs.mapper.NoteCommentMapper;
import com.eesujie.xcs.service.NoteCommentService;
import com.eesujie.xcs.service.UserService;
import com.eesujie.xcs.util.IPUtils;
import com.eesujie.xcs.util.PojoUtils;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 笔记评论表 服务实现类
 * </p>
 *
 * @author eesujie
 * @since 2023-04-19
 */
@Service
public class NoteCommentServiceImpl extends ServiceImpl<NoteCommentMapper, NoteCommentPO> implements NoteCommentService {

    @Resource
    private IPUtils ipUtils;

    @Resource
    private UserService userService;

    @Override
    public List<NoteCommentVO> getCommentsByNoteId(long noteId) {
        var map = getBaseMapper().getCommentsByNoteId(noteId).stream()
                .collect(Collectors.groupingBy(NoteCommentPO::getParentId));
        if (map.size() == 0) return Collections.emptyList();
        var list = map.get(0L).stream().map(this::parseVO).toList();
        list.forEach(vo -> vo.setChildren(map.getOrDefault(vo.getId(), Collections.emptyList()).stream().map(this::parseVO).toList()));
        return list;
    }

    public NoteCommentVO parseVO(NoteCommentPO po) {
        NoteCommentVO vo = PojoUtils.parseVO(po);
        var user = userService.getById(po.getUserId());
        vo.setAvatar(user.getAvatar());
        vo.setNickname(user.getNickname());
        vo.setLocation(ipUtils.getCity(user.getIpv4()));
        return vo;
    }
}
